/**
 * 
 */
package es.aradesh.ministryassist.logic.visit;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.provider.BaseColumns;
import es.aradesh.ministryassist.db.DbAdapter;
import es.aradesh.ministryassist.db.HomeColumns;
import es.aradesh.ministryassist.logic.ministry.Home;
import es.aradesh.ministryassist.logic.ministry.Street;
import es.aradesh.ministryassist.logic.ministry.StreetBuilder;

/**
 * @author xmorales
 * 
 */
public class RevisitBuilder {
	public static long createRevisit(DbAdapter db, String name,
			Street strParent, Home building, String owner) {
		int status = Home.STATUS_RETURN;
		
		long buildingId = building != null ? building.getId()
				: Home.NOT_IN_BUILDING;
		long id = -1;
		if (!"".equals(name)) {
			if (name.matches("[0-9]*"))
				// name is a number and needs a 4 number mask to allow a correct
				// orderBy filter in DB
				while (name.length() < 4)
					name = "0".concat(name);
			id = db.insertHome(name, strParent.getId(), buildingId, 0, 0,
					status, owner);
		}
		return id;
	}

	public static Revisit getRevisitById(DbAdapter db, long id) {
		Revisit result = null;
		ContentValues cv = db.selectById(DbAdapter.TABLE_HOME, id);
		result = new Revisit(id, StreetBuilder.getStreetById(db, cv.getAsLong(
				HomeColumns.STREET_ID).longValue()), null, cv
				.getAsString(HomeColumns.NAME), cv.getAsInteger(
				HomeColumns.STATUS).intValue(), cv
				.getAsString(HomeColumns.OWNER));
		return result;
	}

	public static List<Revisit> getRevisitsList(DbAdapter db) {
		List<Revisit> result = new ArrayList<Revisit>();
		Revisit temp = null;
		String[] cols = new String[] { BaseColumns._ID };
		Cursor c = db.selectTable(DbAdapter.TABLE_HOME, cols,
				HomeColumns.STATUS + " = " + Home.STATUS_GIVED + " OR "
						+ HomeColumns.STATUS + " = " + Home.STATUS_RETURN,
				HomeColumns.NAME);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			temp = getRevisitById(db, c.getLong(c
					.getColumnIndex(BaseColumns._ID)));
			c.moveToNext();
			result.add(temp);
		}
		return result;
	}
}
